package com.lushu.helpers
{
	import com.lushu.data.TilesetImage;
	import com.lushu.info.ApplicationData;
	import com.lushu.typedArrays.ArrayList;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import parts.renderer.ChargementBox;
	
	public class VetementReader extends EventDispatcher
 	{
		private static var VETEMENT_LIST : ArrayList
		
		private var toLoad_ : int = 0;
		private var box_ : ChargementBox;
		
		public function VetementReader(box : ChargementBox)
		{
			box_ = box;
			var XML_URL : String = ApplicationData.BASE_LOCATION+"/"+ApplicationData.VETEMENT_DIRECTORY+"/discovery.php";
			var myXMLURL : URLRequest = new URLRequest(XML_URL);
			var myLoader : URLLoader = new URLLoader(myXMLURL);
			myLoader.addEventListener("complete", dirListed, false, 0, true);
		}
			
		private function dirListed(event : Event):void
		{
			box_.setSubLabel("Vetement : liste chargée");
			var tilesetString : String = event.target.data;
			var tilesetList : Array = tilesetString.split(":");
			var tilesetName : String;
			var currentTileset : TilesetImage;
			toLoad_ = tilesetList.length;
			VETEMENT_LIST = new ArrayList(0, TilesetImage);
					
           	for (var i:int = 0; i < tilesetList.length; i++) 
           	{
				if(tilesetList[i] == "")
					toLoad_--;
				else
				{
					currentTileset = new TilesetImage(tilesetList[i], box_, ApplicationData.VETEMENT_DIRECTORY);
    				currentTileset.addEventListener("tilesetLoaded", tilesetLoaded, false, 0, true);
	    			
					VETEMENT_LIST.addItem(currentTileset);
				}
           	}
		}
		
		private function tilesetLoaded(e : Event) : void
		{
			toLoad_--;
			if(toLoad_ == 0)
			{
				dispatchEvent(new Event("allVetementLoaded"));
			}
		}
		
		public static function getTileset() : ArrayList
		{
			return VETEMENT_LIST;
		}
	}
}